/*
 * Copyright (c) 2017. 恒昌互联网运营中心.
 */
package com.credithc.eagleeye.console.job;
import com.credithc.eagleeye.config.EagleESMonitorConfig;
import com.credithc.eagleeye.console.factory.ESFactory;
import com.credithc.eagleeye.console.mail.MailConfig;
import com.credithc.eagleeye.console.mail.SendFileMail;
import com.credithc.eagleeye.vo.RpcTraceInfoVo;
import com.credithc.framework.es.util.ElasticSearchUtil;
import com.credithc.framework.utils.date.DateTools;
import com.credithc.framework.utils.json.FastJsonConvert;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2017年02月09日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
@Component("errorAlertJob")
public class ErrorAlertJob {
    private final static String subject_format = "%s [%s-env] 鹰眼ERROR信息";
    private final static String platformNames[]=MailConfig.MAIL_ALERT_PLATFORMS;
    //每2分钟发送
    public void execute() throws Exception {
        ElasticSearchUtil elasticSearchUtil = ESFactory.getInstance();

        for(String platformName:platformNames) {
            //long toTime = System.currentTimeMillis();
            Date today = DateTools.getSysDate();
            long toTime = today.getTime();
            //2分钟前
            long formTime = toTime - TimeUnit.MINUTES.toMillis(EagleESMonitorConfig.EAGLE_MONITOR_ALERT_MINUTE_AGO);
            //搜索条件
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("result", "ERROR"));
            boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("platformName", platformName));
            //过滤器
            //BoolFilterBuilder boolFilterBuilder = FilterBuilders.boolFilter();
            if (formTime != 0) {
                boolQueryBuilder.must(QueryBuilders.rangeQuery("requestDateTime").from(formTime));
            }
            if (toTime != 0) {
                boolQueryBuilder.must(QueryBuilders.rangeQuery("requestDateTime").to(toTime));
            }
            //排除定时任务
            boolQueryBuilder.mustNot(QueryBuilders.matchPhraseQuery("serviceName", "taskIceService"));
            //FilteredQueryBuilder queryBuilder = QueryBuilders.filteredQuery(boolQueryBuilder,boolQueryBuilder);
            List<SortBuilder> sortBuilderList = new ArrayList<>();
            SortBuilder sortBuilder0 = SortBuilders.fieldSort("requestDateTime").order(SortOrder.DESC);
            sortBuilderList.add(sortBuilder0);
            int pageSize = 1000;
            int from = 0;
            List<RpcTraceInfoVo> list =
                    elasticSearchUtil.search(
                            RpcTraceInfoVo.class,
                            EagleESMonitorConfig.EAGLE_MONITOR_ES_INDEX,
                            EagleESMonitorConfig.EAGLE_MONITOR_ES_TYPE,
                            boolQueryBuilder,
                            sortBuilderList,
                            from,
                            pageSize);
            for(RpcTraceInfoVo vo : list) {
                vo.setRequestDateTime(vo.getRequestDateTime().replace("T", " ").substring(0, 23));
            }
            long count = elasticSearchUtil.count(EagleESMonitorConfig.EAGLE_MONITOR_ES_INDEX, EagleESMonitorConfig.EAGLE_MONITOR_ES_TYPE, boolQueryBuilder);
            String format_stat = "";
            if (list != null && list.size() > 0) {
                StringBuffer sb = new StringBuffer();
                format_stat = String.format("%s至%s,总计错误条数：" + list.size() + "条。\n",
                        DateTools.FormatDate19(new Date(formTime)),
                        DateTools.FormatDate19(new Date(toTime)));
                sb.append(format_stat);
                for(int i = 0; i < list.size(); i++) {
                    sb.append("第" + (i + 1) + "条:" + FastJsonConvert.convertObjectToJsonWithPrettyFormat(list.get(i)) + "\n");
                }
                try {
                    String errorJson=sb.toString();
                    String subject = String.format(subject_format, platformName.toUpperCase(), MailConfig.MAIL_ENV);
                    String recevier=MailConfig.MAIL_RECEIVER_DLR;
                     if (platformName.equals("hyd")) {
                        recevier = MailConfig.MAIL_RECEIVER_HYD;
                        if(!StringUtils.contains(errorJson,"jsd-late")){
                            recevier = StringUtils.remove(recevier,"caiyongyou160422@credithc.com,");
                        }
                    }
                     if (platformName.equals("csc")) {
                        recevier = MailConfig.MAIL_RECEIVER_CSC;
                    }

                    SendFileMail.sendMail(subject, "EagleEye-Alert", recevier, errorJson, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
